const cartList = document.querySelector(".cartList"); //获取总列表

// 拿到列表页的id根据id去后端读数据、
// const id = location.search.split("?")[1];
let saveGoods = getCookie("goods") ? JSON.parse(getCookie("goods")) : [];
// 2.根据本地存储中的数据，读取商品详情数据

// 立即开启请求，根据id获取指定商品的详情信息
saveGoods.forEach(val => {
    ajax("http://localhost:3000/api", {
        type: "getDetail",
        id: val.id
    }).then(res => {
        // then的第一个回调函数表示成功
        res = JSON.parse(res);
        if (res.code === 1) {
            // console.log(res.data);
            // 准备渲染
            if (res.code === 1) {
                // 3.将读取到的数据渲染到页面
                // console.log(res.data);
                render(res.data, val);
                allPrice();
                allNum();
            }
        } else if (res.code === 0) {
            alert("商品卖完了");
            location.href = "../index.html"
        }
    })
})

function render(data, localData) {


    cartList.innerHTML += `
    <div class="banner-goods-left" index="${data.proId}">
        <div class="banner-infor1">
            <input type="checkbox" class="check"  ${localData.flag ? 'checked' : ''}>
        </div>
        <div class="banner-infor2">
            <img src="${data.img}" alt="">
        </div>
        <div class="banner-infor3">
            <h1>3ce</h1>
            <h2>${data.proName}</h2>
            <h3>规格：${data.detail}</h3>
        </div>
        <div class="banner-infor4">${data.price}</div>
        <div class="banner-infor5">
            <input type="number" value="${localData.num}" class="setNum">
        </div>
        <div class="banner-infor6">${data.price * localData.num}</div>
        <div><i class="iconfont del">&#xeb83;</i></div>
    </div>`;
}
{/* <td><input type="button" value="删除" class="del"></td> */ }

let goods = {};
cartList.addEventListener("click", function (eve) {
    const e = eve ? eve : window.event;
    const target = e.target ? e.target : e.scrElement;
    console.log(target.className);
    if (target.className.indexOf("del") != -1) {
        // 5. 点击删除时，获取当前商品id
        goods.id = target.parentNode.parentNode.getAttribute("index");
        // 删除DOM
        target.parentNode.parentNode.remove();
        // 6. 从本地存储的数据中找到当前id对应的商品
        setLocal(function (i) {
            saveGoods.splice(i, 1);
        });
        all();
    }
})

cartList.addEventListener("input", function (eve) {
    const e = eve ? eve : window.event;
    const target = e.target ? e.target : e.scrElement;
    if (target.className.indexOf("setNum") != -1) {
        goods.id = target.parentNode.parentNode.getAttribute("index");
        goods.num = target.value - 0;
        setLocal(function (i) {
            target.parentNode.parentNode.querySelector('.banner-infor6').innerHTML = goods.num*saveGoods[i].price
            saveGoods[i].num = goods.num;
        });
        all();
    }
})
cartList.addEventListener("change", function (eve) {
    const e = eve ? eve : window.event;
    const target = e.target ? e.target : e.scrElement;
    if (target.className.indexOf("check") != -1) {
        goods.id = target.parentNode.parentNode.getAttribute("index");
        goods.check = target.checked;
        console.log(goods.id,goods.check)
        setLocal(function (i) {
            saveGoods[i].flag = Number(goods.check);
        });
        all();
    }
})

$("#allCheck").change(function () {
    // 修改所有的复选框的选中状态
    for (let i = 0; i < $(".check").length; i++) {
        $(".check")[i].checked = this.checked;
    }
    // 修改所有数据的选中状态
    // goods.forEach(val=>{
    //     val.flag = Number(this.checked)
    // })
    // localStorage.setItem("goods",JSON.stringify(goods))

    setCookie("goods", JSON.stringify(saveGoods.map(val => {
        val.flag = Number(this.checked)
        return val;
    })))
    all();

    // 计算总数量
    // $("#allNum").html(allNum(goods));

    // 计算总价
    // $("#allPrice").html(allPrice(goods));
})













function allPrice() {
    $("#allPrice").html(
        saveGoods.reduce((prev, val) => {
            return prev + (val.flag ? val.num * val.price : 0);
        }, 0) + '￥'
    );
}
function allNum() {
    $("#allNum").html(
        saveGoods.reduce((prev, now) => prev + (now.flag ? now.num : 0), 0)
    );

}
const all = () => {
    allPrice();
    allNum();
}
function setLocal(cb) {
    let i = 0;
    saveGoods.some((val, idx) => {
        i = idx;
        return val.id == goods.id;
    })
    // 操作
    cb(i);
    // 7. 将操作之后的数据，再存回本地存储
    setCookie("goods", JSON.stringify(saveGoods));
}
function ajax(url, data) {
    let str = "";
    for (let i in data) {
        str += `${i}=${data[i]}&`
    }
    url += "?" + str;

    const xhr = new XMLHttpRequest();
    xhr.open("get", url);
    xhr.send();

    return new Promise((resolve, reject) => {
        xhr.onload = function () {
            if (xhr.status === 200) {
                resolve(xhr.responseText);
            } else {
                reject(xhr.status);
            }
        }
    })
}

